import cv2 as cv
import sys
import os
from python_ai.common.xcommon import *
import matplotlib.pyplot as plt
import numpy as np
import time
import datetime


def my_show_img(img, title="no title", trans=None, **kwargs):
    global spn
    spn += 1
    plt.subplot(spr, spc, spn)
    if trans is not None:
        img = trans(img)
    plt.imshow(img, **kwargs)
    plt.axis('off')
    plt.title(title)


img_dir = '../../../../large_data/CV2/lesson/Day03'
img_name = 'sudoku.png'
img_path1 = os.path.join(img_dir, img_name)

spr = 2
spc = 5
spn = 0
plt.figure(figsize=[15, 6])

sep('load')
img = cv.imread(img_path1, cv.IMREAD_GRAYSCALE)
print('original shape', img.shape)
H, W = img.shape
H2 = (H - 1) // 2
W2 = (W - 1) // 2
my_show_img(img, 'original', cmap='gray')
img_ori = img.copy()

sep('blur')
img = cv.medianBlur(img, 5)
my_show_img(img, 'original=>medianBlur', cmap='gray')

sep('thresholds')
ret, th1 = cv.threshold(img, 127, 255, cv.THRESH_BINARY)
my_show_img(th1, 'thresh 127-255', cmap='gray')
th2 = cv.adaptiveThreshold(img, 255, cv.ADAPTIVE_THRESH_MEAN_C, cv.THRESH_BINARY, 11, 2)
my_show_img(th2, 'thresh adaptive mean', cmap='gray')
th3 = cv.adaptiveThreshold(img, 255, cv.ADAPTIVE_THRESH_GAUSSIAN_C, cv.THRESH_BINARY, 11, 2)
my_show_img(th3, 'thresh adaptive gaussian', cmap='gray')

hist_data = [img_ori, img, th1, th2, th3]
for hist in hist_data:
    spn += 1
    plt.subplot(spr, spc, spn)
    print(hist.shape)
    plt.hist(hist.ravel(), 256)